<template>
  <div class="host-manage">
    <h1 class="page-title neon-text">主机管理</h1>

    <!-- 操作栏 -->
    <el-card style="margin-bottom: 20px">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input 
            v-model="searchText" 
            placeholder="搜索主机名或IP地址"
            clearable
            @clear="loadHosts"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="showDialog()">
            <el-icon><Plus /></el-icon> 添加主机
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 主机列表 -->
    <el-card>
      <el-table :data="hosts" v-loading="loading" style="width: 100%">
        <el-table-column prop="hostname" label="主机名" min-width="120" fixed="left" />
        <el-table-column prop="ip_address" label="IP地址" min-width="130" />
        <el-table-column prop="port" label="端口" width="70" />
        <el-table-column prop="os_type" label="操作系统" min-width="100">
          <template #default="{ row }">
            <span>{{ row.os_type || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cpu_cores" label="CPU" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.cpu_cores" type="info" size="small">
              {{ row.cpu_cores }} 核
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="memory_size" label="内存" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.memory_size" type="warning" size="small">
              {{ formatMemory(row.memory_size) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="disk_size" label="磁盘" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.disk_size" type="success" size="small">
              {{ row.disk_size }} GB
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="100" />
        <el-table-column prop="host_group_name" label="主机组" min-width="100" />
        <el-table-column prop="project_name" label="项目" min-width="100" />
        <el-table-column prop="environment_name" label="环境" min-width="100" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openTerminal(row.id)">
              连接
            </el-button>
            <el-button size="small" @click="testConnection(row.id)">
              测试
            </el-button>
            <el-button size="small" @click="showDialog(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteHost(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="主机名">
          <el-input v-model="form.hostname" />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="form.ip_address" />
        </el-form-item>
        <el-form-item label="SSH端口">
          <el-input v-model.number="form.port" type="number" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="主机组">
          <el-select v-model="form.host_group" clearable placeholder="请选择">
            <el-option 
              v-for="item in hostGroups" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="form.project" clearable placeholder="请选择">
            <el-option 
              v-for="item in projects" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="环境">
          <el-select v-model="form.environment" clearable placeholder="请选择">
            <el-option 
              v-for="item in environments" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作系统">
          <el-input v-model="form.os_type" placeholder="如：CentOS 7.9 / Ubuntu 20.04" />
        </el-form-item>
        <el-form-item label="CPU核心数">
          <el-input-number v-model="form.cpu_cores" :min="1" :max="256" placeholder="核心数" />
        </el-form-item>
        <el-form-item label="内存大小">
          <el-input-number v-model="form.memory_size" :min="512" :step="512" placeholder="MB" />
          <span style="margin-left: 10px; color: var(--cyber-text-dim)">MB</span>
        </el-form-item>
        <el-form-item label="磁盘大小">
          <el-input-number v-model="form.disk_size" :min="1" :step="10" placeholder="GB" />
          <span style="margin-left: 10px; color: var(--cyber-text-dim)">GB</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { hostAPI, hostGroupAPI, projectAPI, environmentAPI } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const searchText = ref('')
const hosts = ref([])
const hostGroups = ref([])
const projects = ref([])
const environments = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('添加主机')
const form = ref({
  hostname: '',
  ip_address: '',
  port: 22,
  username: '',
  password: '',
  host_group: null,
  project: null,
  environment: null,
  os_type: '',
  cpu_cores: null,
  memory_size: null,
  disk_size: null,
  status: 'offline',
  description: ''
})
const editId = ref(null)

const loadHosts = async () => {
  loading.value = true
  try {
    const res = await hostAPI.getList()
    hosts.value = res.results || res
  } catch (error) {
    ElMessage.error('加载主机列表失败')
  } finally {
    loading.value = false
  }
}

const loadOptions = async () => {
  try {
    const [groups, projs, envs] = await Promise.all([
      hostGroupAPI.getList(),
      projectAPI.getList(),
      environmentAPI.getList()
    ])
    hostGroups.value = groups.results || groups
    projects.value = projs.results || projs
    environments.value = envs.results || envs
  } catch (error) {
    console.error('加载选项失败:', error)
  }
}

const showDialog = (row = null) => {
  if (row) {
    dialogTitle.value = '编辑主机'
    editId.value = row.id
    form.value = {
      hostname: row.hostname,
      ip_address: row.ip_address,
      port: row.port,
      username: row.username,
      password: '',
      host_group: row.host_group,
      project: row.project,
      environment: row.environment,
      os_type: row.os_type || '',
      cpu_cores: row.cpu_cores || null,
      memory_size: row.memory_size || null,
      disk_size: row.disk_size || null,
      status: row.status,
      description: row.description || ''
    }
  } else {
    dialogTitle.value = '添加主机'
    editId.value = null
    form.value = {
      hostname: '',
      ip_address: '',
      port: 22,
      username: '',
      password: '',
      host_group: null,
      project: null,
      environment: null,
      os_type: '',
      cpu_cores: null,
      memory_size: null,
      disk_size: null,
      status: 'offline',
      description: ''
    }
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    if (editId.value) {
      await hostAPI.update(editId.value, form.value)
      ElMessage.success('更新成功')
    } else {
      await hostAPI.create(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadHosts()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteHost = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这台主机吗？', '警告', {
      type: 'warning'
    })
    await hostAPI.delete(id)
    ElMessage.success('删除成功')
    loadHosts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const testConnection = async (id) => {
  try {
    const res = await hostAPI.testConnection(id)
    if (res.status === 'success') {
      ElMessage.success('连接测试成功')
    }
  } catch (error) {
    ElMessage.error('连接测试失败: ' + (error.response?.data?.message || '未知错误'))
  }
}

const openTerminal = (hostId) => {
  router.push(`/terminal/${hostId}`)
}

const getStatusType = (status) => {
  const map = {
    'online': 'success',
    'offline': 'info',
    'maintenance': 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护中'
  }
  return map[status] || status
}

const formatMemory = (sizeInMB) => {
  if (!sizeInMB) return '-'
  if (sizeInMB >= 1024) {
    return `${(sizeInMB / 1024).toFixed(1)} GB`
  }
  return `${sizeInMB} MB`
}

onMounted(() => {
  loadHosts()
  loadOptions()
})
</script>

<style scoped>
.host-manage {
  padding: 20px;
}

.page-title {
  font-size: 32px;
  margin-bottom: 30px;
  color: var(--cyber-primary);
  font-family: 'Courier New', monospace;
  letter-spacing: 3px;
}
</style>
